<template>
  <div class="contract-management">
    <div style="margin-bottom: 15px;">
      <h3>合同管理</h3>
    </div>

    <el-table :data="contractData" style="width: 100%" border>
      <el-table-column prop="contractId" label="合同编号" width="200"></el-table-column>
      <el-table-column prop="clientName" label="租户"></el-table-column>
      <el-table-column prop="contractType" label="合同类型"></el-table-column>
      <el-table-column prop="contractAmount" label="合同金额"></el-table-column>
      <el-table-column prop="startDate" label="开始日期"></el-table-column>
      <el-table-column prop="stopDate" label="结束日期"></el-table-column>
      <el-table-column prop="contractStatus" label="状态">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.contractStatus)">{{ scope.row.contractStatus }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="viewContract(scope.row)">查看</el-button>
          <el-button size="mini" type="warning" @click="showRenewDialog(scope.row)"
            :disabled="scope.row.contractStatus !== '即将逾期' && scope.row.contractStatus !== '逾期'">续费</el-button>
          <el-button size="mini" type="warning" @click="refundDeposit(scope.row)"
            :disabled="scope.row.contractStatus !== '已到期'">退押金</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrap">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="prev, pager, next, ->, jumper, ->, sizes, total"
        :total="total" />
    </div>

    <!-- 续费对话框 -->
    <el-dialog title="续费" :visible.sync="renewDialogVisible" width="40%">
      <div>
        <p>合同编号: {{ selectedContract.contractId }}</p>
        <p>总金额: {{ selectedContract.contractAmount }} 元/月</p>
        <p>已付金额: {{ selectedContract.paymentAmount }} 元</p>
        <p>未付金额: {{ selectedContract.unpaidAmount }} 元</p>
      </div>
      <p style="margin-top: 20px;">请选择要续费的月数:</p>
      <div style="margin-top: 20px;">
        <el-input-number v-model="monthsToPay" :min="1" :max="selectedContract.months"></el-input-number>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="renewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePayment">付款</el-button>
      </span>
    </el-dialog>
    <!-- 支付表单容器 -->
    <div id="payment-form-container" style="display: none;"></div>
  </div>
</template>
<script>
import request from '@/utils/request';

export default {
  name: 'ContractManagement',
  data() {
    return {
      currentPage: 1,
      pageSize: 14,
      total: 0,
      contractData: [],
      renewDialogVisible: false,
      selectedContract: {},
      monthsToPay: 1
    }
  },
  created() {
    this.fetchContracts();
  },
  methods: {
    fetchContracts() {
      const params = {
        page: this.currentPage,
        size: this.pageSize
      };

      request.post('/bill/getContractList', params)
        .then(response => {
          console.log('获取合同数据成功:', response);

          if (response.code == 200) {
            this.contractData = response.data.records.map(record => {
              record.unpaidAmount = record.contractAmount - record.paymentAmount;
              return record;
            });
            this.total = response.data.total;
          } else {
            console.error('获取合同数据失败:', response.data.message);
          }
        })
        .catch(error => {
          console.error('请求合同数据时发生错误:', error);
        });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchContracts();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchContracts();
    },
    viewContract(row) {
      this.$router.push({
        path: '/contract/detail',
        query: { contractId: row.contractId }
      });
    },
    showRenewDialog(row) {
      this.selectedContract = row;
      this.monthsToPay = 1;  // 默认选择1个月
      this.renewDialogVisible = true;
    },
    handlePayment() {
      if (this.monthsToPay <= 0) {
        this.$message.error('请选择要续费的月数');
        return;
      }

      request.post('/billPay/payOrder', { billId: this.selectedContract.contractId, type: 2 })
        .then(response => {
          console.log('获取支付页面成功:', response);

          if (response.code == 200) {
            const paymentPage = response.data;
            if (paymentPage) {
              this.renderPaymentForm(paymentPage);
            } else {
              console.error('支付页面内容为空');
              this.$message.error('支付页面内容为空');
            }
          } else {
            console.error('获取支付页面失败:', response.data.message);
            this.$message.error('获取支付页面失败');
          }
        })
        .catch(error => {
          console.error('请求支付页面时发生错误:', error);
          this.$message.error('请求支付页面时发生错误');
        });
    },
    renderPaymentForm(paymentPage) {
      const container = document.getElementById('payment-form-container');
      container.innerHTML = paymentPage;
      container.style.display = 'block';

      // 自动提交表单
      const form = container.querySelector('form');
      if (form) {
        form.submit();
      } else {
        console.error('表单未找到');
        this.$message.error('表单未找到');
      }
    },
    openPaymentPage(paymentPage) {
      console.log('打开支付页面:', paymentPage);  // 添加调试信息
      const newWindow = window.open('', '_blank');
      if (newWindow) {
        newWindow.document.write(paymentPage);
        newWindow.document.close();
      } else {
        console.error('无法打开新窗口');
        this.$message.error('无法打开新窗口');
      }
    },
    refundDeposit(row) {
      if (row.contractStatus === '已到期') {
        this.$confirm('确定要退押金该合同吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 调用退押金接口
          request.post('/bill/refundDeposit', { contractId: row.contractId })
            .then(response => {
              console.log('退押金成功:', response);
              this.$message.success('退押金成功');
              this.fetchContracts();  // 重新加载数据
            })
            .catch(error => {
              console.error('退押金失败:', error);
              this.$message.error('退押金失败');
            });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消退押金'
          });
        });
      }
    },
    getStatusType(status) {
      switch (status) {
        case '进行中':
          return 'success';
        case '逾期':
          return 'danger';
        case '即将逾期':
          return 'warning';
        case '即将到期':
          return 'warning';
        case '已到期':
          return 'info';
        default:
          return '';
      }
    }
  }
}
</script>
